<template>
  <div class="AI-score">
    <div class="AI-score-banner">
      <div class="teach-info-box ai_b_s">
        <div class="teach-info">
          <div class="ai-tit clear">
            <span>筛选</span>
            <el-popover class="fr" width="300" trigger="click" v-model="popoverVisible">
              <el-form :model="scoreForm" ref="scoreForm" class="scoreForm">
                <el-form-item prop="grade_id">
                  <el-select v-model="scoreForm.grade_id" @change="getGrade" placeholder="年级" size="mini">
                    <el-option v-for="item in orgLevel3" :label="item.name" :value="item.id" :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="class_id">
                  <el-select v-model="scoreForm.class_id" placeholder="班级" size="mini">
                    <el-option v-for="item in orgClass" :label="item.name" :value="item.id" :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="subject_id">
                  <el-select v-model="scoreForm.subject_id" placeholder="科目" size="mini">
                    <el-option v-for="(item, index) in orgSubject" :label="item.name" :value="item.id" :key="index"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item prop="exam_type">
                  <el-select v-model="scoreForm.exam_type" placeholder="考试类型" size="mini">
                    <el-option v-for="item in examTypeOptions" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="keyword">
                  <el-input v-model="scoreForm.keyword" placeholder="试卷名" size="mini"></el-input>
                </el-form-item>
                <el-form-item class="btns-item">
                  <el-button type="primary" size="mini" @click="seachBtn">确定</el-button>
                  <el-button size="mini" @click="resetForm('scoreForm')">重置</el-button>
                </el-form-item>
              </el-form>
              <el-button type="primary" size="medium" slot="reference">筛选</el-button>
            </el-popover>
          </div>
        </div>
        <div class="score-table-con">
          <table class="score_table">
            <tr>
              <th>考试类型</th>
              <th>试卷名称</th>
              <th>科目</th>
              <th>年级/班级</th>
              <th>平均分</th>
              <th>分析</th>
            </tr>
            <template>
              <tr v-for="(item,index) of examData" :key="index">
                <td>{{item.exam_type}}</td>
                <td>{{item.name}}</td>
                <td>{{item.subject}}</td>
                <td>{{item.grade}}</td>
                <td>{{item.score}}</td>
                <td>
                  <el-radio v-model="radio" :label="index" @change="check_exam(item.id)"></el-radio>
                </td>
              </tr>
              <tr v-if="examData.length==0">
                <td colspan="6">暂时没有发现数据</td>
              </tr>
            </template>
          </table>
        </div>
        <div class="AI-class-pageBox clear">
          <!-- <el-pagination background v-if="total_number > scoreForm.page_size" :pager-count="10" @current-change="change_page" :page-size="scoreForm.page_size" :current-page="scoreForm.page_index" layout="prev, pager, next" :total="total_number">
          </el-pagination> -->
        </div>
      </div>
      <div class="mark-focus-box ai_b_s">
        <div class="ai-tit mark-focus-l">
          <span>成绩与参与度分析</span>
          <div id="focus_map" style="width: 100%;height:404px;"></div>
        </div>
        <div class="mark-focus-r">
          <table class="mark-focus-table">
            <thead>
              <tr>
                <th>学生名单</th>
              </tr>
            </thead>
            <tbody>
              <tr :class="{t_active:index==active_index}" v-for="(item,index) of checked_StuScore" :key="index" @click="check_stu(index,item)">
                <td>{{item.StuName}}</td>
              </tr>
              <div class="noDataTip" v-show="checked_StuScore.length==0">未发现相关数据</div>
            </tbody>
          </table>
        </div>
      </div>
      <div class="score-info-box ai_b_s">
        <div class="ai-tit">
          <span>分数段分布</span>
        </div>
        <div id="score_map" style="width: 100%;height:344px;"></div>
      </div>
      <div class="single-score-box ai_b_s">
        <div class="ai-tit single-score-l">
          <span>个体成绩趋势</span>
          <div id="single_map" style="width: 100%;height:390px;"></div>
        </div>
        <div class="single-score-r">
          <div class="single-pic">
            <i><img v-if="single_stu_score.picture!=null" :src="BASE_URL+single_stu_score.picture" alt="头像"></i>
            <span>{{single_stu_score.StuName}}</span>
            <span v-if="single_stu_score.StuName==null">姓名</span>
          </div>
          <table class="single-score-table">
            <thead>
              <th>
              <td>试卷</td>
              <td>分数</td>
              </th>
            </thead>
            <tbody>
              <tr :class="{t_active_s:index==single_score_inx}" v-for="(item,index) of Exam_data" :key="index" @click="check_score(index,item)">
                <td>{{item.name}}</td>
                <td>{{item.score}}</td>
              </tr>
              <div class="noDataTip" v-show="checked_StuScore.length==0">未发现相关数据</div>
            </tbody>
          </table>
        </div>
      </div>

    </div>
  </div>
</template>
   
<script>
const echarts = require("echarts/lib/echarts");
require("echarts/lib/chart/map");
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
export default {
  data() {
    return {
      // 授课信息列表：
      scoreForm: {
        grade_id: "",
        class_id: "",
        subject_id: "",
        exam_type: "",
        keyword: "",
        page_index: 1,
        page_size: 7,
      },
      total_number: 0,
      examData: [],
      radio: null,
      // 筛选弹窗框：
      orgLevel3: [],//年级
      orgClass: [],//班级
      orgSubject: [],//科目
      examTypeOptions: [],
      popoverVisible: false,
      scoreId: null,
      // echarts图表:
      myChart1: null,
      myChart2: null,
      myChart3: null,

      checked_class: {}, //选中的班数据
      checked_StuScore: [], //选中班的学生分数集
      class_focus_data: [], //一个班所有学生的参与度+分数
      single_stu_score: {}, //单个学生
      stu_name_check: null,
      lessson_scores: [], //一个班所有的分数集
      scores_count: [], //各分数段的数量
      active_index: 0, //成绩关注度分析图：默认选中第一个学生
      focus_data: [], //成绩关注图的坐标
      single_score_inx: 0,//成绩趋势图，选中的单个分数索引
      Exam_data: [], //课程+分数
      examName: null,
      maxScore: 100,//试卷总分
      // 个体成绩趋势图
      // 个人考试的试卷总分
      singleMaxScore: 100
    };
  },
  created() {
    this.init();
    this.scoreList();
    this.getGrade();
    this.getExamType();
  },
  mounted() {
    let scoreId = sessionStorage.getItem("scoreId");
    if (scoreId != undefined) {
      this.scoreId = scoreId;
      this.check_exam(scoreId);
    }
    //成绩关注度分析
    this.focus_map();
    //分数段分布
    this.score_map();
    //个体成绩趋势
    this.single_map();
    this.init();
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.popoverVisible = false;
      this.scoreList();
    },
    //获取年级
    getGrade() {
      this.orgSubject = [];
      let success = res => {
        let data = res.data;
        if (data.length === 0) {
          return;
        }
        this.orgLevel3 = data;
        this.orgLevel3.unshift({ id: 0, name: '全部年级' });
        this.scoreForm.class_id = "";
        this.scoreForm.subject_id = "";
        this.getClass();
        this.getSubject();
      };
      this.$ajax({
        url: "api/org/all_grade",
        method: "get",
        params: {
        },
        func: {
          success: success
        }
      });
    },
    // 获取班级
    getClass() {
      let success = res => {
        this.orgClass = res.data;
        this.orgClass.unshift({ id: 0, name: '全部班级' });
      }
      this.$ajax.get("api/org/org", {
        params: {
          level: 4,
          pid: this.scoreForm.grade_id,
          direction: "balance"
        },
        func: { success: success }
      });
    },
    //获取科目
    getSubject() {
      let success = res => {
        this.orgSubject = res.data;
        this.orgSubject.unshift({ id: 0, name: '全部科目' });
      };
      this.$ajax({
        url: "api/cate/subject",
        method: "get",
        params: {
          type: 2,
          org_id: this.scoreForm.grade_id,
          status: 1
        },
        func: {
          success: success
        }
      });
    },
    //获取试题类型
    getExamType() {
      let success = res => {
        let data = res.data;
        this.examTypeOptions = data;
        this.examTypeOptions.unshift({ id: 0, name: '全部类型' });
      };
      this.$ajax({
        url: "api/test/test_source",
        method: "get",
        params: {
        },
        func: {
          success: success
        }
      });
    },
    // echerts图标自适应
    init() {
      window.addEventListener("resize", () => {
        this.myChart1.resize();
        this.myChart2.resize();
        this.myChart3.resize();
      });
    },
    // 筛选确定按钮
    seachBtn() {
      this.scoreForm.page_index = 1;
      this.scoreList();
    },
    //授课信息列表
    scoreList() {
      let success = res => {
        // console.log(res)
        this.examData = res.data.data;
        this.scoreForm.page_index = parseInt(res.data.page_index);
        this.total_number = res.data.total_number;
        this.popoverVisible = false;//筛选弹窗
        //根据之前保存的考试的id，设置选中状态
        let _data = res.data.data;
        // console.log(this.scoreId)
        if (this.scoreId != null) {
          for (let i = 0; i < _data.length; i++) {
            if (this.scoreId == _data[i].id) {
              this.radio = i;
            }
          }
        }
      };
      this.$ajax({
        url: "api/ai/exam_list",
        method: "get",
        params: this.scoreForm,
        func: { success: success }
      });
    },
    //授课信息列表的分页
    change_page(val) {
      this.radio = null;
      this.scoreForm.page_index = val;
      this.scoreList();
    },
    //分析：选中一个考试
    check_exam(_id) {
      let success = res => {
          let _res= res.data;
        // console.log(_res)
        //选择授课
        this.checked_class = [];
        this.checked_StuScore = [];
        this.class_focus_data = [];

        this.focus_data = [];
        this.Exam_data = [];
        this.single_stu_score = {};
        this.single_score_inx = 0;

        this.maxScore = _res.score;//试卷总分
        this.checked_class = _res.data;
        this.checked_StuScore = _res.data;
        //缓存、获取考试id
        sessionStorage.setItem("scoreId", _id);
        this.scoreId = _id;

        // console.log(this.checked_StuScore)
        if (_res.data.length != 0) {//课程信息列表选中考试之后，若获取到详细的考试信息，那成绩参与度分析列表默认选中第一项
          this.check_stu(0, deep_clone(_res.data)[0]);
        }
        //选择一个课程，获取学生的，[参与度,分数]
        let st_arr = _res.data;
        let _scores = [];
        let count_data = [0, 0, 0, 0, 0];
        for (var i = 0; i < st_arr.length; i++) {
          var _arr = [];
          _arr.push(st_arr[i].JoinDegree);
          _arr.push(st_arr[i].Score);
          _scores.push(st_arr[i].Score);
          this.class_focus_data.push(_arr);
        }
        // console.log(this.class_focus_data)
        //计算五个分数段，分别有多少人
        for (let j = 0; j < _scores.length; j++) {
          if (_scores[j] < this.maxScore * 0.6) {
            count_data[0]++;
          } else if (_scores[j] <= this.maxScore * 0.69) {
            count_data[1]++;
          } else if (_scores[j] <= this.maxScore * 0.79) {
            count_data[2]++;
          } else if (_scores[j] <= this.maxScore * 0.89) {
            count_data[3]++;
          } else if (_scores[j] <= this.maxScore) {
            count_data[4]++;
          }
        }
        this.scores_count = count_data;
        this.focus_map();
        this.score_map();
        this.single_map();
      };
      this.$ajax({
        url: "api/ai/exam_info",
        method: "get",
        params: {
          id: _id
        },
        func: { success: success }
      });

    },
    //选择学生
    check_stu(inx, item) {
      this.stu_name_check = item.StuName;
      this.focus_data = [];
      this.Exam_data = [];
      this.active_index = inx;
      this.single_score_inx = 0;
      //   ------
      this.single_stu_score = item;
      this.single_stu_score.pictue = item.pictue;
      // -----------
      let j_arr = [];//参与度
      let s_arr = [];//分数
      let e_arr = [];//试卷名
      let id_arr = [];//试卷的id
      // console.log(item.PersonalScore)
      if (item.PersonalScore.length != 0) {
        this.examName = item.PersonalScore.ExamName[0];//选中学生后，个体成绩趋势图也默认提示第一次考试的名字
        j_arr = item.PersonalScore.JoinDegree;
        s_arr = item.PersonalScore.Score;
        e_arr = item.PersonalScore.ExamName;
        id_arr = item.PersonalScore.ExamId;
        // console.log(j_arr)
        this.change_arr(j_arr, s_arr, this.focus_data, 1);//拼接成绩与参与度，点的坐标
        this.change_arr(e_arr, s_arr, this.Exam_data, 2);
        //重组数组（个体成绩趋势图：试卷数组添加，试卷id）：
        for (let i = 0; i < this.Exam_data.length; i++) {
          this.Exam_data[i].id = id_arr[i];
        }
        //选中学生，该学生考过的试卷id在ExamId数组中，用id去匹配所有考试数据，找出学生考过的试卷的总分是多少，取考试总分的最大值
        let allMaxScore = [];////选中学生考过的试卷，所有的总分
        let examId = item.PersonalScore.ExamId;//选中学生考过的试卷，所有的试卷id
        for (let j = 0; j < examId.length; j++) {
          for (let k = 0; k < this.examData.length; k++) {
            if (this.examData[k].id === examId[j]) {
              allMaxScore.push(this.examData[k].max_score)
            }
          }
        }
        this.singleMaxScore = Math.max.apply(null,allMaxScore);//取试卷总分数组中分数的最大值

        this.check_score(0, this.Exam_data[0]);//切换学生的时候，书生个人成绩列表默认选中第一项
      }
      this.focus_map();
      this.single_map();
    },
    //选中单个学生成绩列表的的某次考试的试卷
    check_score(inx, item) {
      this.examName = item.name;
      this.single_score_inx = inx;
      this.single_map();
    },
    //拼接符合图标格式的数组
    change_arr(arr1, arr2, origin_arr, type) {
      for (var i = 0; i < arr1.length; i++) {
        for (var j = 0; j < arr2.length; j++) {
          if (j == i && type == 1) {
            var _arr = [];
            _arr.push(arr1[i]);
            _arr.push(arr2[j]);
            origin_arr.push(_arr);
          }
          if (j == i && type == 2) {
            var _obj = {};
            _obj.name = arr1[i];
            _obj.score = arr2[j];
            origin_arr.push(_obj);
          }
        }
      }
    },
    //成绩与参与度分析
    focus_map() {
      this.myChart1 = echarts.init(document.getElementById("focus_map"));
      this.myChart1.off('click');//解决：点击散点时，切换效果不流畅，切换显示等几秒钟才出来（实际累积循环点击死循环了）的问题
      var option = {
        xAxis: {
          name: "参与度%",
          axisLine: {
            lineStyle: {
              color: "#fff"
            }
          },
          axisLabel: {
            textStyle: {
              color: "#fff" //坐标值得具体的颜色
            }
          },
          splitLine: {
            show: false
          },
          min: 0,
          max: 100,
          type: "value"
        },
        yAxis: {
          name: "分数",
          axisLine: {
            lineStyle: {
              color: "#fff"
            }
          },
          axisLabel: {
            textStyle: {
              color: "#fff"
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "#3C5F95"
            }
          },
          min: 0,
          max: this.maxScore,
          type: "value"
        },
        series: [
          {
            type: "scatter",
            symbolSize: 10,
            color: "#08fcff",
            data: this.class_focus_data
          },
          {
            type: "effectScatter",
            symbolSize: 10,
            color: "#FFC101",
            data: [
              [
                this.single_stu_score.JoinDegree,
                this.single_stu_score.Score
              ]
            ],
            showEffectOn: "render",
            rippleEffect: {
              brushType: "stroke"
            },
            label: {
              normal: {
                position: "right",
                distance: 0,
                show: true,
                formatter: [
                  "{title|学 生：}" + [this.stu_name_check],
                  "{join|参与度：}" + [Math.round(this.single_stu_score.JoinDegree * 100) / 100] + "%",
                  "{score|分 数：}" + [Math.round(this.single_stu_score.Score * 100) / 100] + "分",
                ].join("\n"),
                padding: [10, 15],
                position: [15, -65],//提示框相对位置：right/top
                fontSize: 14,
                color: "#fff",
                backgroundColor: "rgba(0,0,0,0.5)",
                borderRadius: 5,
                rich: {
                  title: {
                    color: "#fff",
                    align: "center",
                  },
                  join: {
                    color: "#fff",
                    height: 20
                  },
                  score: {
                    color: "#fff",
                  }
                }
              }
            }
          }
        ]
      };
      this.myChart1.setOption(option);
      //给散点添加点击事件
      let that = this;
      this.myChart1.on('click', function (params) {
        let _inx = params.dataIndex;//获取被点击的点的索引
        let _item = that.checked_StuScore[_inx];
        that.check_stu(_inx, _item);//学生名单列表选中状态改变
      })
      this.myChart1.resize();
    },
    // 分数段分布
    score_map() {
      // 拼接分数段字符串，分别按试卷总分60%，70%，80%，90%，100%划分5个区间
      let scoreP1 = this.maxScore * 0.6 + "分以下";
      let scoreP2 = this.maxScore * 0.6 + "-" + this.maxScore * 0.7;
      let scoreP3 = this.maxScore * 0.7 + "-" + this.maxScore * 0.8;
      let scoreP4 = this.maxScore * 0.8 + "-" + this.maxScore * 0.9;
      let scoreP5 = this.maxScore * 0.9 + "-" + this.maxScore;
    //   console.log(this.scores_count)
      this.myChart2 = echarts.init(document.getElementById("score_map"));
      this.myChart2.setOption({
        color: ["#1792FF"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: "2%",
          right: "8%",
          bottom: "0%",
          containLabel: true
        },
        xAxis: [
          {
            name: "分数",
            type: "category",
            data: [scoreP1, scoreP2, scoreP3, scoreP4, scoreP5],
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              lineStyle: {
                color: "#fff",
                width: 1
              }
            }
          }
        ],
        yAxis: [
          {
            name: "人数",
            type: "value",
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: "#3C5F95"
              }
            },
            axisLine: {
              lineStyle: {
                color: "#fff",
                width: 1
              }
            }
          }
        ],
        series: [
          {
            name: "人数",
            type: "bar",
            barWidth: "60%",
            data: this.scores_count,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  formatter: '{c}' + '人',
                  color: '#fff'
                },
                shadowBlur: 80,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
          }
        ]
      });
      this.myChart2.resize();
    },
    //个体成绩趋势
    single_map() {
    //   console.log(this.focus_data)
      let _join = 0, _score = 0;
      if (this.focus_data.length != 0) {
        _join = this.focus_data[this.single_score_inx][0];
        _score = this.focus_data[this.single_score_inx][1];
      }
      this.myChart3 = echarts.init(document.getElementById("single_map"));
      this.myChart3.off('click');
      this.myChart3.setOption({
        xAxis: {
          name: "参与度%",
          axisLine: {
            lineStyle: {
              color: "#fff"
            }
          },
          splitLine: {
            show: false
          },
          min: 0,
          max: 100,
          type: "value"
        },
        yAxis: {
          name: "分数",
          axisLine: {
            lineStyle: {
              color: "#fff"
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "#3C5F95"
            }
          },
          min: 0,
          max: this.singleMaxScore,
          type: "value"
        },
        series: [
          {
            name: "成绩",
            symbolSize: 20,
            data: this.focus_data,
            type: "scatter",
            symbolSize: 10,
            color: "#FFC101"
          },
          {
            name: "当前考试的成绩",
            type: "effectScatter",
            symbolSize: 10,
            color: "#08fcff",
            data: [this.focus_data[this.single_score_inx]],
            showEffectOn: "render",
            rippleEffect: {
              brushType: "stroke"
            },
            label: {
              normal: {
                position: "right",
                distance: 0,
                show: true,
                formatter: [
                  // "{title|学 生：}" + [this.stu_name_check],
                  this.examName,
                  "{join|参与度：}" + _join + "%",
                  "{score|分 数：}" + _score + "分",
                ].join("\n"),
                padding: [10, 15],
                position: [15, -65],//提示框相对位置：right/top
                fontSize: 14,
                color: "#fff",
                backgroundColor: "rgba(0,0,0,0.5)",
                borderRadius: 5,
                rich: {
                  title: {
                    color: "#fff",
                    align: "center",
                  },
                  join: {
                    color: "#fff",
                    height: 20
                  },
                  score: {
                    color: "#fff",
                  }
                }
              }
            }
          }
        ]
      });
      let that = this;
      this.myChart3.on('click', function (params) {
        let _inx = params.dataIndex;//获取被点击的点的索引
        let _item = that.Exam_data[_inx];
        that.check_score(_inx, _item);//列表选中状态改变
      })
      this.myChart3.resize();
    },

  }
};
</script>
